<?php

// *** Documentation
/*______________________________________________________________________________

  Bafflegate Site Metric Script
  Version 0.02
  
  Last Update: August 2007
  Author: Tom at klenwell@gmail.com
  
  SUMMARY
  a crude test
  
  NOTES
  to test, call directly: http://localhost/BAFFLEGATE/version0/log.m03.php?bafflekey=direct
		
______________________________________________________________________________*/


// *** Pre-Script (core settings, includes)
/*____________________________________________________________________________*/

// ** Meta Variables
	
  // timer
  $_tx1 = microtime();
  
  // syntax declarations
  define('DS', DIRECTORY_SEPARATOR);
  
  // pre-script events
  if ( ob_get_level() == 0 ) ob_start();
  session_start();
	

// ** Core Page Settings
$_DIR['root'] = '../';

	
// ** Includes
require_once('functions.m02.inc.php');
require_once('../oss/adodb_lite/adodb.inc.php');
#require_once('../oss/browscap/Browscap.php');

	
/*============================================================================*/



// *** Data (triggers, flags, HTML, and other variables)
/*____________________________________________________________________________*/

// ** Controller Flags

  // config settings
  $cue = 'baffleticket';
  $test_table = 'log_m02';
  $cache_path = $_DIR['root'] . 'cache_bin/';

  // Triggers (Page Events)
  $_TRIGGER['cx_baffler'] = 0;
  $_TRIGGER['log_visit'] = 0;
  $_TRIGGER['log_session'] = 0;
  $_TRIGGER['log_seo'] = 0; 
  $_TRIGGER['log_referrer'] = 0;
  $_TRIGGER['log_visitor'] = 0;


// ** Data
	

// ** Output


/*============================================================================*/



// *** Controllers (handles requests and sets event triggers)
/*____________________________________________________________________________*/

// GET Triggers
// this script will be called either from a javascript file or an img tag of 
// the page and thus should require some kind of GET value to trigger construction
// of the baffler object
if ( !empty($_GET[$cue]) )
{
  $_TRIGGER['cx_baffler'] = 1;
  $_TRIGGER['log_visit'] = 1;
}
else
{
  // can we assume that this is an error or an unwanted direct call to this file?
  $_TRIGGER['redirect'] = 1;
}

// debug
if ( 0 )
{
  echo '<script type="text/javascript">alert("'. $_SERVER['PHP_SELF'] . ' called")</script>';
  die();
}

/*============================================================================*/



// *** Events (trigger-controlled events)
/*____________________________________________________________________________*/

// construct object
if ( $_TRIGGER['cx_baffler'] )
{
  // create object
  #$Baffler = new Bafflegate();
  $Baffler = new stdClass();
  
  // get data
  #$Baffler->get_visitor_data();
  
  // baffleticket, session
  $Baffler->baffleticket = $_GET[$cue];
  $Baffler->uts = time();
  $Baffler->session_uid = 0;
  #1 - if ( $Baffler->has_active_session() ) $Baffler->session_uid = $Baffler->_SESSION['baffle_session_uid'];
  #2 - if ( $Baffler->has_active_session_cookie() )$_COOKIE['baffleticket'] = $Baffler->baffleticket (and last 30 min) $Baffler->session_uid = $COOKIE['bsuid'];
  #3 - if ( $Baffler->select_active_session() ) SELECT session_uid from log matching ip, domain, last 30min $Baffler->session_uid = DB[session_uid]
  #else $Baffler->session_uid = 0;
    
  // site data
  $Baffler->visited_url = get_visited_url();
  $Baffler->visited_domain = get_base_domain($Baffler->visited_url);
  $Baffler->visited_subdomain = get_subdomain($Baffler->visited_url);
  $Baffler->visited_qstring = get_qstring($Baffler->visited_url);
  $Baffler->visited_title = ( !empty($_GET['ttl']) ) ? urldecode($_GET['ttl']) : '';
  $Baffler->referrer_url = ( !empty($_GET['ref']) ) ? urldecode($_GET['ref']) : '';
  $Baffler->referrer_domain = get_url_domain($Baffler->referrer_url);
  $Baffler->referrer_qstring = get_qstring($Baffler->referrer_url);
  
  // seo / keywords
  $_SEO['BOT'] = array('google', 'yahoo', 'msn', 'aol', 'feedster', 'lycos', 'altavista', );
  $_SEO['CUE'] = array('q', 'as_q', 'MT', 'query', 'p', 's', 'userQuery', 'query');
  // check to see if referrer query string
  // check to see if referrer host is a bot : stristr($host, $arr_engines[$cnt][2])
  // if seobot, explode qstring at '&'
  // for each qpair: explode at '=', if in_array(Q1, SEO['CUE']), KW[] = array(cleanup(Q2), Q1)
  // if count(KW) = 1, keywords = KW[0]
  // if count(KW) > 1, foreach KWas K, len = strlen(K0) / if len > maxlen maxlen = len, keywords = K0, query_cue = K1
  
  // visitor data
  $Baffler->client_ip = get_client_ip();
  $Baffler->hostname = get_hostname_by_ip($Baffler->client_ip);
  $Baffler->proxy = get_proxy();
  if ( !empty($Baffler->proxy) )
  {
    if ( !$Baffler->proxy_ip = get_client_ip_simple() ) $Baffler->proxy_ip = $Baffler->client_ip;
    $Baffler->proxy_hostname = get_hostname_by_ip($Baffler->proxy_ip);
  }  
  
  // agent data
  $Baffler->agent_string = $_SERVER['HTTP_USER_AGENT'];
  $Baffler->agent_hash = md5($Baffler->agent_string);
  $Baffler->js_enabled = ( isset($_GET['jsa']) ) ? $_GET['jsa'] : '-1';
  $Baffler->os = ( !empty($_GET['uos']) ) ? urldecode($_GET['uos']) : '';
  $Baffler->screen_size = ( !empty($_GET['ssz']) ) ? urldecode($_GET['ssz']) : '';
  $Baffler->screen_depth = ( !empty($_GET['sdp']) ) ? urldecode($_GET['sdp']) : '';
  
  // get browser data with browscap class (http://garetjax.info/projects/browscap/)
  #$Baffler->BrowsCap = new Browscap($cache_path);
  #$_DATA['BROWSCAP'] = $Baffler->BrowsCap->getBrowser();
  #$Baffler->client_browser = $_DATA['BROWSCAP']['Browser'];
  #$Baffler->browser_ver = $_DATA['BROWSCAP']['Version'];
  #$Baffler->platform = $_DATA['BROWSCAP']['Platform'];
  
  // pull database data
  #$_DBR = $Baffler->select_account_info();
  #SELECT from account WHERE baffleticket = $Baffler->baffleticket
  
  // debug
  if ( 1 )
  {
    $dump = print_r($Baffler,1);
    $out = "<pre>$dump</pre>";
    print $out;
    write_file("this is a test of " . __FILE__ . ' at ' . date('r') . "\n" . $dump, 'baffledump.txt', $overwrite=1);
    $_TRIGGER['log_visit'] = 0;  
  }
}

// log visit
if ( $_TRIGGER['log_visit'] ) 
{
  // set cancel code
  $Baffler->cancel_code = 0;
  if ( strpos($Baffler->visited_url, $_DBR['domain']) == FALSE ) $Baffler->cancel_code = 1;
  elseif ( $Baffler->baffleticket != $_DBR['baffleticket'] ) $Baffler->cancel_code = 2;
  elseif ( $_COOKIE['baffle_ign'] == $_DBR['baffleticket'] ) $Baffler->cancel_code = 3;

  // log visit
  #$Baffler->log_visit();
  
    // identify cancels -- we still record them but assign cancel code as SELECT hook
    // cancel codes:
    // 1 - GET[baffleticket] <> DB[baffleticket]
    // 2 - COOKIE['baffle_ignore'] = baffleticket    
    // 3 - strpos(url, DB[domain]) === FALSE
    // else 0
    
    // get site id (referer?)
    // hit db
    // new session?  set log_session trigger
    
    // data bind
    $_INSERT = array
    (
      $Baffler->baffle_key,
      $Baffler->visited_url,
      $Baffler->visited_qstring,
      $Baffler->referrer,
      $Baffler->uts,
      $Baffler->client_ip,
      $Baffler->hostname,
      $Baffler->proxy,      
      $Baffler->proxy_ip,
      $Baffler->proxy_hostname,
      $Baffler->agent_string,
      $Baffler->agent_hash,
      $Baffler->js_enabled,
      $Baffler->browser,
      $Baffler->browser_version,
      $Baffler->os,
      $Baffler->screen_size,
      $Baffler->screen_depth,
    );
    
    // insert
    $_SQL['insert'] = <<<SQL
INSERT INTO $test_table
( baffle_key, url, query_string, referrer_url, uts, client_ip, 
  client_host, proxy, proxy_ip, proxy_host, agent_string, agent_hash, 
  js_enabled, browser, version, os, screen_size, screen_depth ) 
VALUES ( ?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?,?, ?,?,? )
SQL;

    // settings
    $db_user = 'root';
    $db_pass = 'root';
    $db_name = 'bafflegate';
    $db_server = 'localhost';
    
    // create object
    $_pw = urlencode($db_pass);
    $_flags = 2;
    $_dsn = "mysql://$db_user:$_pw@$db_server/$db_name?clientflags=$_flags";
    if ( !$DBO =& ADONewConnection($_dsn) ) 
    {
      trigger_error('unable to connect to database [' . $db_name . ']', E_USER_WARNING);
    }
    
    // run query
    if ( !$DBO_r = $DBO->Execute($_SQL['insert'], $_INSERT) )
    {
      trigger_error($DBO->ErrorMsg(), E_USER_WARNING);
      trigger_error($_SQL['insert']);
      print_r($Baffler);
      return 0;
    }
    else
    {
      $insert_id = $DBO->Insert_ID();
      echo "insert id: $insert_id";
    } 
}

// log session
if ( $_TRIGGER['log_session'] ) 
{
  // log session
  #$Baffler->log_session();
    // is filtered
    // hit db
    // new referral? set log_referrer
    // new search referral? set log_seo
    // new visitor? set log_visitor
    
  // set cookie
}

/*============================================================================*/


// *** Output (handles requests and sets event triggers)
/*____________________________________________________________________________*/


/*============================================================================*/



// *** Post-Script (close HTML, flush buffer, and other backend operations)
/*____________________________________________________________________________*/

// ** Flush Buffer
while (ob_get_level() > 0) { ob_end_flush(); }
flush();
$_HTML['flush'] = "<!-- buffer flushed at " . date('r') . " -->";

// ** Page Timer
$_tx2 = microtime();
$_tx3 = number_format(((substr($_tx2,0,9)) + (substr($_tx2,-10)) - (substr($_tx1,0,9)) - (substr($_tx1,-10))),4); 
$_HTML['timer'] = "\n<!-- script [id: {$_PAGE['id']}] generated in $_tx3 s -->";

/*============================================================================*/
// * That's All Folks!
?>
